package com.victor.coder;

import com.victor.common.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 *  定义数据的传输协议,基于netty的实现
 * Created by DJJ on 2019/3/12.
 */
//对传递的消息进行编码,传递的是请求/响应对象
//先编码,再传输到服务端进行解码
public class RpcEncoder extends MessageToByteEncoder {
    //传递的数据对象类型
    private Class genericClass;

    public RpcEncoder(Class genericClass){
        this.genericClass=genericClass;
    }
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf out) throws Exception {
            if (genericClass.isInstance(msg)){
                //将对象序列化为字节数组
                byte[] serialize = SerializationUtil.serialize(msg);
                // 把数据写入到下一个通道(channel)或者是发往服务端
                out.writeBytes(serialize);
            }
    }
}
